package cn.joeg.app.web.core.auth;

import cn.joeg.app.dto.OptInfo;
import cn.joeg.app.web.cache.UserCacheService;
import cn.joeg.app.web.db.user.UserFightService;
import cn.joeg.app.web.db.user.UserService;
import cn.joeg.app.web.util.RespConst;
import com.ecfront.dew.common.JsonHelper;
import com.ecfront.dew.common.Resp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * TODO:写点说明把
 *
 * @author Joeg
 * @email 840459673@qq.com
 * @date 2018/4/14
 */

@RestController
@Api(value = "认证", description = "针对所有登陆的游戏用户做授权")
@RequestMapping(value = "/auth/")
public class AuthAdaptationController {


    private static final Logger logger = LoggerFactory.getLogger(AuthAdaptationController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private UserFightService userFightService;
    @Autowired
    private UserCacheService userCacheService;

    @PostMapping(value = "/public/core/auth/login")
    @ApiOperation(value = "登录", notes = "登录功能，若没有注册进行注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginReq", value = "登录请求", paramType = "body", dataType = "AuthReq", required = true),
    })
    public Resp<OptInfo> login(@RequestBody AuthReq req) {
        logger.info("auth login req: {}", JsonHelper.toJson(req));
        /*if (loginReq.getDeviceId() == null || loginReq.getDeviceId().isEmpty() ||
                loginReq.getServiceId() == 0 ||
                loginReq.getMac() == null || loginReq.getMac().isEmpty() ||
                loginReq.getIdfa() == null || loginReq.getIdfa().isEmpty() ||
                loginReq.get_360id() == null || loginReq.get_360id().isEmpty()) {

            return Resp.badRequest("请输入登录登录信息");
        }*/

        String deviceId = req.getDeviceId();
        int serverId = req.getServiceId();
        String mac = req.getMac();
        String idfa = req.getIdfa();
        String _360id = req.get_360id();

        //***360相关处理 start
        if (_360id != null && _360id.isEmpty()) {
            userService._360Login(_360id, deviceId);
            deviceId = _360id;
        }
        //***360相关处理 end

        List<UserService.UserVO> userList = userService.queryUserByDeviceId("*", deviceId);


        //结果code
        int result = 0;
        UserService.UserVO userVO = null;
        if (userList.size() > 0) {
            //有帐号 表示：登录
            userVO = getMaxCompanyLevelUser(serverId, userList);
//            user.initValue(userMap);
        } else {
            // 没有帐号 表示：新用户注册
            result = userService.createUser(deviceId, mac, idfa);
            if (result == 0) {
                // 注册失败
                return Resp.customFail(String.valueOf(0), RespConst.REGISTER_FAIL);
            }
            // 注册成功
            userList = userService.queryUserByDeviceId("*", deviceId);
            if (userList != null && userList.size() > 0) {
                userVO = userList.get(0);
            }
        }



        if (userVO.getBlocked() == 1) {// 用户被禁
            return Resp.customFail(String.valueOf(2), RespConst.USER_BANNED);
        }


        UserFightService.UserFighterVO userFighterVO = userFightService.queryUserFighterByUserid(userVO.getId());
        String formation = userFighterVO.getFormation() == null || userFighterVO.getFormation().isEmpty() ? "" : userFighterVO.getFormation().trim();
        String token = userCacheService.refreshToken(userVO.getId());

//        AuthResp.LoginResp loginResp = new AuthResp.LoginResp(formation, token);
        OptInfo optInfo = new OptInfo();
        optInfo.setToken(token);
        //serviceId
        optInfo.setAccountCode(String.valueOf(serverId));
        //deviceId
        optInfo.setLoginId(deviceId);
        optInfo.setLastLoginTime(new Date());
//        optInfo.setExt(JsonHelper.toJsonString(staffVO));
        CacheManager.addToken(optInfo);
        logger.info("auth login success: {}", JsonHelper.toJson(optInfo));

        return Resp.success(optInfo);

    }

    /**
     * 得到最大公司等级的用户
     *
     * @param serverId
     * @param userList
     * @return
     */
    private UserService.UserVO getMaxCompanyLevelUser(int serverId, List<UserService.UserVO> userList) {
        UserService.UserVO userMap = null;
        for (UserService.UserVO userVO : userList) {
            // 取最大等级公司
            if (userMap == null || userMap.getCompanylevel() < userVO.getCompanylevel()) {
                userMap = userVO;
            }

            long userid = (long) userVO.getId();
            // 服务器ID 亿位数
            if (serverId <= 20) {
                if (userid / 100000000 == serverId) {
                    userMap = userVO;
                    break;
                }
            } else {
                if (userid / 1000000 == serverId) {
                    userMap = userVO;
                    break;
                }
            }
        }
        return userMap;
    }


}
